<!--
 * @LastEditTime : 2022-10-31 16:42:16
 * @FilePath     : /pyy/src/views/chemistry/add/index.vue
 * @Description  : 化学分析 > 化学分析检测(新增化学分析)
-->
<template>
  <div id="chemistry-add">
    <van-nav-bar title="化学分析检测" left-arrow @click-left="goBack" />

    <div class="contaniner">
      <van-form
        label-width="180px"
        input-align="right"
        error-message-align="right"
        validate-trigger="onChange"
        scroll-to-error
        @submit="handleSubmit"
      >
        <div class="form-group">
          <van-field
          class="mandatory"
            name="consignorW"
            label="委托人"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.consignorW"
          />
          
          <van-field
          class="mandatory"
            name="clientName"
            label="委托方客户名称"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.clientName"
          />
          <van-field
          class="mandatory"
            name="principalPhone"
            label="委托人电话"
            placeholder="请填写电话号码"
            autocomplete="off"
            :rules="[
              {
                validator: (val) =>
                  val
                    ? /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(
                        val
                      )
                    : true,
                message: '请输入正确的电话号码',
              },
              { required: true, message: '不能为空' }
              
            ]"
            v-model="form.principalPhone"
          />
          <van-field
            name="principalAdd"
            label="委托人地址"
            class="mandatory"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.principalAdd"
          />
          <popup-select
            name="contractReview"
            class="mandatory"
            label="简化合同评审"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请选择"
            :options="relationData.whetherOptions"
            :default-props="{
              label: 'name',
              value: 'id',
            }"
            v-model="form.contractReview"
          />
          <!-- <van-field
            name="contractCode"
            label="合同编码"
            placeholder="请填写"
            autocomplete="off"
            v-model="form.contractCode"
            :readonly="simplifyTheContractReview"
          /> -->
          <popup-select
            name="organization"
            label="检验机构"
            class="mandatory2"
            :rules="[{ required: true, message: '不能为空' }]"
            placeholder="请选择"
            :options="relationData.organizationOptions"
            :default-props="{
              label: 'name',
              value: 'id',
            }"
            v-model="form.organization"
          />
          <popup-select
            disavled
            name="toWay"
            label="样品送样方式"
            placeholder="请选择"
            :defaultSelect="defaultSelect"
            :options="relationData.toWayOptions"
            :default-props="{
              label: 'name',
              value: 'id',
            }"
            v-model="form.toWay"
          />
        
<!--          <van-field
            readonly
            type="number"
            name="analysisSum"
            label="分析检测金额"
            placeholder="请输入数字"
            autocomplete="off"
            :value="analysisSum"
          />-->
          <van-field name="require" label="是否同意检验要求">
            <template #input>
              <van-radio-group direction="horizontal" v-model="form.require">
                <van-row type="flex" justify="space-between">
                  <van-col
                    v-for="item in relationData.whetherOptions"
                    :key="item.id"
                  >
                    <radio-circle :name="item.id" icon-size="16px">
                      {{ item.name }}
                    </radio-circle>
                  </van-col>
                </van-row>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-model="form.means"
            name="means"
            label="手动输入方法"
            placeholder="请输入"
            autocomplete="off"
            :disabled="isRequire"
          />
          <van-field name="dispose" label="样品是否按实验室规定处理">
            <template #input>
              <van-radio-group direction="horizontal" v-model="form.dispose">
                <van-row type="flex" justify="space-between">
                  <van-col
                    v-for="item in relationData.whetherOptions"
                    :key="item.id"
                  >
                    <radio-circle :name="item.id" icon-size="16px">
                      {{ item.name }}
                    </radio-circle>
                  </van-col>
                </van-row>
              </van-radio-group>
            </template>
          </van-field>
          <van-field name="urgent" label="是否加急">
            <template #input>
              <van-radio-group direction="horizontal" v-model="form.urgent">
                <van-row type="flex" justify="space-between">
                  <van-col
                    v-for="item in relationData.whetherOptions"
                    :key="item.id"
                  >
                    <radio-circle :name="item.id" icon-size="16px">
                      {{ item.name }}
                    </radio-circle>
                  </van-col>
                </van-row>
              </van-radio-group>
            </template>
          </van-field>
          <calendar
            name="takeDate"
            label="计划客户取报告日期"
            placeholder="请选择日期"
            v-model="form.takeDate"
          />
         
        </div>
        <detailed
          v-for="(item, index) in form.child"
          :key="'detailed_' + index"
          :index="index"
          :show-delete="index < form.child.length - 1"
          :form.sync="item"
          :sample-state="relationData.sampleStateOptions"
          :detection-big="relationData.detectionOptions"
          @delete="(i) => form.child.splice(i, 1)"
          @copy="(i) => form.child.push(JSON.parse(JSON.stringify(form.child[i])))"
        />
        <van-button
          block
          type="default"
          class="btn-add-detailed"
          icon="plus"
          native-type="button"
          @click.stop="handleAddDetailed"
        >
          新增明细
        </van-button>
        <div class="btn-groups">
          <van-button
            class="btn-submit"
            round
            block
            type="info"
            native-type="submit"
          >
            提交
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
import Detailed from "./components/detailed.vue";
import { Toast } from "vant";
import api from "@/http/api";
const NO_DATA_TIP = "暂无数据";
export default {
  name: "ChemistryAdd",
  components: {
    Detailed,
  },
  data() {
    return {
      arrList:[],
      defaultSelect:{},
      // columns: [],
      relationData: {
        // 检验机构
        organizationOptions: [],
        // 样品送达方式
        toWayOptions: [],
        // 检测项目大类
        detectionOptions: [],
        // 是否
        whetherOptions: [],
        // 化学检测物料试样状态
        sampleStateOptions: [],
      },

      form: {
        consignorW: "",
        clientName: "",
        principalPhone: "",
        principalAdd: "",
        contractReview: "",
        contractCode: "",
        organization: "",
        toWay: "",
        analysisSum: "",
        require: "",
        means: "",
        dispose: "",
        urgent: "",
        takeDate: "",
        theAttachment:null,
        child: [
          //{
          //  sampleName: "",
          //  sampleCode: "",
          //  sampleState: "",
          //  specification: "",
          //  detectionBig: "",
          //  samplePreparation: "",
          //  content: "",
          //  cost: null,
          //  costSamplePreparation: "",
          //  choose: "",
          //  remark: "",
          //},
        ],
      },
    };
  },
  computed: {
    columns() {
      const result = this.relationData.toWayOptions.map((item) => item.name);
      return result.length ? result : [NO_DATA_TIP];
    },
   
    // 是否同意检验要求
    isRequire() {
      const result = this.relationData.whetherOptions.find(
        (item) => item.id == this.form.require
      );
      return result ? result.name == "是" : false;
    },

    // 是否简化合同评审
    simplifyTheContractReview() {
      const result = this.relationData.whetherOptions.find(
        (item) => item.id == this.form.contractReview
      );
      return result ? result.name == "否" : false;
    },
    // 是否加急
    isUrgent() {
      const result = this.relationData.whetherOptions.find(
        (item) => item.id == this.form.urgent
      );
      return result ? result.name == "是" : false;
    },
    // 分析检测金额
    analysisSum() {
      /**
       * 是否加急
       * - 是: 费用 乘以2
       * - 否: 费用是多少，就是多少
       */
      return ((this.form.analysisSum ?? 0) * (this.isUrgent ? 2 : 1) * 1.06).toFixed(2) || null;
    },
  },
  watch: {
    "form.child": {
      handler(child) {
        var count = 0
        child.forEach(item => {
         if(item.samplePreparation == '1' ) {
          count++
         }      
        });
        var samplePMoney = count * 20
        // 分析检测金额: 明细表金额合集
        this.form.analysisSum = child.reduce(
          (result, current) => (result += current.cost),
          0
        ) + samplePMoney;
      },
      deep: true,
    },
    // "form.toWay":{
    //   handler(newV,oldV){
    //     console.log('newV1,oldV2 :>> ', newV,oldV);
    //   },
    //   deep:true,
    //   immediate:true
    // },
    // "form.contractReview":{
    //   handler(newV,oldV){
    //     console.log('newV,oldV :>> ', newV,oldV);
    //   },
    // }
  },
  created() {
    this.initRelationData();
  },
  mounted() {


  },
  methods: {
    onConfirm(value) {
      this.value = value;
      this.showPicker = false;
    },
    getDate(){
    var myDate = new Date();	//创建Date对象
    var Y = myDate.getFullYear();   //获取当前完整年份
    var M = myDate.getMonth() + 1;  //获取当前月份
    var D = myDate.getDate();   //获取当前日1-31
    var H = myDate.getHours();  //获取当前小时
    var i = myDate.getMinutes();    //获取当前分钟
    var s = myDate.getSeconds();    //获取当前秒数
    // 月份不足10补0
    if(M < 10){
        M = '0' + M;
    }
    // 日不足10补0
    if(D < 10){
        D = '0' + D;
    }
    // 小时不足10补0
    if(H < 10){
        H = '0' + H;
    }
    // 分钟不足10补0
    if(i < 10){
        i = '0' + i;
    }
    // 秒数不足10补0
    if(s < 10){
        s = '0' +s;
    }
    // 拼接日期分隔符根据自己的需要来修改
    var nowDate = Y+'-'+M+'-'+ D
    return nowDate

    },


    afterRead(file){
      let formData = new FormData();
      formData.append("file", file.file);
      this.form.theAttachment = formData
      // api.equipment.uploadAFile(formData).then((res) => {
      //   const { code, data = [] } = res.data;
      //   console.log("uploadAFileres :>> ", res.data.data);
      //   if (code === 200) {
      //     let arr = [];
      //     res.data.data.forEach((item) => {
      //       arr.push(this.enumerationTraversal(item));
      //     });
      //     this.form.child = arr;
      //   }
      // });
    },
    /**
     * 返回
     */
    goBack() {
      this.$router.replace("/chemistry");
    },

    /**
     * 初始化 关联数据
     */
    initRelationData() {
      const toast = Toast.loading({
        duration: 0,
        forbidClick: true,
      });
      api.chemistry
        .getEnum()
        .then((res) => {
          const { code, data, msg } = res.data || {};
          if (code !== 200) return Toast.fail(msg);

          this.relationData.organizationOptions = data["化学检测地点"] || [];
          this.relationData.toWayOptions = data["样品送样方式"] || [];
          this.defaultSelect =this.relationData.toWayOptions[0]//默认选择第一个
          this.form.toWay = this.relationData.toWayOptions[0].id//默认选择第一个

          this.relationData.detectionOptions = data["化学检测项目大类"] || [];
          this.relationData.whetherOptions = data["是否"] || [];
          this.relationData.sampleStateOptions =
            data["化学检测物料试样状态"] || [];

          this.setDefaultData();
        })
        .finally(() => {
          setTimeout(toast.clear, 500);
        });
    },

    /**
     * 设置 默认数据
     */
    setDefaultData() {
      // 默认选中 是
      const result = this.relationData.whetherOptions[0] || {};
      this.form.require = result.id;
      this.form.dispose = result.id;
      this.form.urgent = result.id;
    },

    /**
     * 点击 新增明细表
     */
    handleAddDetailed() {
      this.form.child.push({
        sampleName: "",
        sampleCode: "",
        sampleState: "",
        specification: "",
        detectionBig: "",
        samplePreparation: "",
        content: "",
        cost: null,
        costSamplePreparation: "",
        choose: "",
        remark: "",
      });
    },

    /**
     * 点击 提交
     */
    handleSubmit() {
      const toast = Toast.loading({
        duration: 0,
        forbidClick: true,
      });
      console.log('object1 :>> ', this.getCurrentMonthLastDay(new Date()));
      console.log('object2 :>> ', this.getCurrentMonthLastDay2(new Date()));
      console.log('object3 :>> ', this.getCurrentMonthLastDay3(new Date()));
      console.log('object4 :>> ', this.getCurrentMonthLastDay4(new Date()));
      if(this.getDate() === this.getCurrentMonthLastDay(new Date())){
       
        Toast.fail("月末最后四天内，不能提交");
      }else if(this.getDate() === this.getCurrentMonthLastDay2(new Date())){
        Toast.fail("月末最后四天内，不能提交");
      }else if(this.getDate() === this.getCurrentMonthLastDay3(new Date())){
        Toast.fail("月末最后四天内，不能提交");
      }else if(this.getDate() === this.getCurrentMonthLastDay4(new Date())){
        Toast.fail("月末最后四天内，不能提交");
      }
      else{
        api.chemistry
        .addProcess({
          ...this.form,
          analysisSum: this.analysisSum,
        })
        .then((res) => {
          const { code, msg } = res.data || {};
          if (code !== 200) return Toast.fail(msg);
          Toast.success("新增成功");
          setTimeout(this.goBack, 1000);
        })
        .finally(() => {
          setTimeout(toast.clear, 500);
        });
        console.log("submit", this.form);
      }



   
    },
         // 获取当月最后一天
      getCurrentMonthLastDay() {
      let date = new Date();
      let currentMonth = date.getMonth();
      let nextMonth = ++currentMonth;
      let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      let oneDay = 1000 * 60 * 60 * 24;
      let lastTime = new Date(nextMonthFirstDay - oneDay);
      let month = parseInt(lastTime.getMonth() + 1);
      let day = lastTime.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + day;
    },
         // 获取当月到数第二天
         getCurrentMonthLastDay2() {
      let date = new Date();
      let currentMonth = date.getMonth();
      let nextMonth = ++currentMonth;
      let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      let oneDay = 1000 * 60 * 60 * 24;
      let lastTime = new Date(nextMonthFirstDay - oneDay);
      let month = parseInt(lastTime.getMonth() + 1);
      let day = lastTime.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + ((day*1)-1);
    },
         // 获取当月到数第3天
         getCurrentMonthLastDay3() {
      let date = new Date();
      let currentMonth = date.getMonth();
      let nextMonth = ++currentMonth;
      let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      let oneDay = 1000 * 60 * 60 * 24;
      let lastTime = new Date(nextMonthFirstDay - oneDay);
      let month = parseInt(lastTime.getMonth() + 1);
      let day = lastTime.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + ((day*1)-2);
    },
         //获取当月到数第4天
      getCurrentMonthLastDay4() {
      let date = new Date();
      let currentMonth = date.getMonth();
      let nextMonth = ++currentMonth;
      let nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
      let oneDay = 1000 * 60 * 60 * 24;
      let lastTime = new Date(nextMonthFirstDay - oneDay);
      let month = parseInt(lastTime.getMonth() + 1);
      let day = lastTime.getDate();
      if (month < 10) {
        month = "0" + month;
      }
      if (day < 10) {
        day = "0" + day;
      }
      return date.getFullYear() + "-" + month + "-" + ((day*1)-3);
    },
  },
};
</script>

<style lang="less" scoped>
.theTestReport{
  position: relative;
  &::after{
    content: '[上传附件]';
    display: block;
    position: absolute;
    top: 16px;
    left: 116px;
    font-size: 14px;
    width: max-content;
    height: auto;
    color: gray;
  }
}
#chemistry-add {
  width: 100vw;
  height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;

  /deep/ .van-nav-bar {
    .van-nav-bar__title {
      font-family: "Inter";
      font-style: normal;
      font-weight: 600;
      font-size: 18px;
      line-height: 20px;
      text-align: center;
      letter-spacing: -0.24px;
      color: #333333;
    }

    .van-nav-bar__content {
      .van-nav-bar__left {
        i {
          font-size: 20px;
          color: #999999;
        }
      }
    }
  }

  .contaniner {
    width: 100%;
    height: 0;
    flex: 1;
    overflow-y: auto;

    /deep/ .van-form {
      .form-group {
        box-sizing: border-box;
        padding: 0 12px;
        background: #ffffff;
      }
      .mandatory{
            position: relative;
            &::after{
                content: '*';
                display: block;
                position: absolute;
                left: 5px;
                top: 14px;
                font-size: 16px;
                color: red;
                transform: scale(1);

            }
        }
        .mandatory2{
            position: relative;
            &::after{
                content: '*';
                display: block;
                position: absolute;
                left: 5px;
                top: 20px;
                font-size: 16px;
                color: red;
                transform: scale(1);

            }
        }
      .van-field {
        font-family: "Inter";
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 24px;
        color: #666666;
        padding: 12px 4px;
        padding-left: 15px !important;
        border-bottom: 1px solid #e8e8e8;

        .van-field__label {
          span {
            white-space: nowrap;
          }
        }

        .van-field__value {
          .van-field__body {
            .van-field__control {
              .van-radio-group {
                width: 80%;

                .van-row {
                  width: 100%;

                  .van-radio {
                    margin: 0;

                    .van-radio__icon {
                      height: 16px;
                      width: 16px;

                      .svg-icon {
                        height: 16px;
                        width: 16px;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }

      .btn-add-detailed {
        font-family: "ABeeZee";
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 20px;
        text-align: center;
        letter-spacing: -0.24px;
        color: #0e86d1;
        border: none;
      }
    }

    .btn-groups {
      width: 100%;
      box-sizing: border-box;
      padding: 18px 12px;

      .btn-submit {
        background: #0e86d1;
        border-radius: 4px;
        font-family: "Inter";
        font-style: normal;
        font-weight: 400;
        font-size: 16px;
        line-height: 19px;
        color: #ffffff;
      }
    }
  }
}
</style>
